//https://leetcode.cn/problems/remove-element/
package codeRandomThoughts.Test27移除元素;

public class Solution {
    public int removeElementBadVersion(int[] nums, int val) {
        int tail = nums.length - 1;
        for (int i = 0; i < nums.length; i++) {
            //所有等于val的元素都被移除了,没必要继续遍历
            if (i == tail) {
                break;
            }
            if (nums[i] == val) {
                for (int j = tail; j > i; j--) {
                    if (nums[j] != val) {
                        //tail用来记录当前最后一个参与处理的值的位置
                        nums[i] = nums[j];
                        nums[j] = val;
                        //更新尾部的位置
                        tail = j - 1;
                        break;
                    }
                }
            }
        }
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == val) {
                return i;
            }
        }
        return nums.length;
    }

    //这个现在还没吃透
    public int removeElementOptimalDoublePointer(int[] nums, int val) {
        //和我一开始的想法很相似,但很明显,我又想的麻烦了
        int left = 0;
        int right = nums.length;
        while (left < right) {
            if (nums[left] == val) {
                nums[left] = nums[right - 1];
                right--;
            } else {
                left++;
            }
        }
        return left;
    }

    public int removeElement(int[] nums, int val) {
        //快慢指针
        int fast = 0;
        int slow = 0;
        //遍历nums数组
        for (fast = 0; fast < nums.length; fast++) {
            //fast每轮都会增大,所以是fast
            //而slow只有满足条件才会增大,所以是slow
            if (nums[fast] != val) {
                nums[slow] = nums[fast];
                slow++;
            }
        }
        return slow;
    }
}
